
import os
import openpyxl
from testapp.common.initPath import DATADIR



class Readexcel(object):
    def __init__(self, filename, sheet_name=None):
        self.filename = os.path.join(DATADIR, filename)
        self.sheet_name = sheet_name
        self.note =  "#"          #注释符号
        self.wb = None

        #opent xlsx
    def openexcel(self):
        self.wb = openpyxl.open(self.filename)
        if self.sheet_name is not None:
            self.sh = self.wb[self.sheet_name]
        #print(*self.sh)
        
        #get data case
    def read_excels(self):    #明天就改这里
        if self.wb is None:
            self.openexcel()
        datas = list(self.sh.rows)
        title = [i.value for i in datas[0]]
        cases = []
        for i in datas[1:]:
            data = [k.value for k in i]
            case = dict(zip(title, data))
            try:
                if str(case['case_id'])[0] is not self.note:        #判断此条用例是否注释掉    以note符号开头，注释掉便不收集、不执行
                    case['sheet'] = self.sh.title
                    cases.append(case)
            except KeyError:
                cases.append(case)
        return cases

    def read_all_excels(self):
        self.openexcel()
        cases = []
        for sheet in self.wb:
            if sheet.title[0] is not self.note:    #过滤掉注意的sheet页
                self.sh = sheet
                cases += self.read_excels()
        return cases

    # def sheet_count(self):
    #     self.openexcel()
    #     count = 0
    #     sheetdict = {}
    #     for sheet in self.wb:
    #         if sheet.title[0] is not self.note:       #判断用例sheet页是否注释掉   以note符号头开头注释，注释掉便不收集、不执行
    #             count += 1
    #             sh = 'sheet' + str(count)
    #             sheetdict[sh] = sheet.title
    #     sheetdict['count'] = count
    #     self.wb.close()
    #     return sheetdict


    def write_excels(self, rows, column, value):
        self.openexcel()
        self.sh.cell(row=rows, column=column, value=value)
        self.wb.save(self.filename)



# sheetdict = {'sheet1': 'register', 'sheet2': 'login', 'sheet3': 'recharge', 'sheet4': 'withdraw', 'sheet5': 'add', 'sheet6': 'audit', 'sheet7': '未覆盖的用例', 'count': 7}
# title = "asdfsdf"
# conf = Config()
# note = conf.get('identifier', 'note')
# if note is title[0]:
#     print('TRUE')
# else:
#     print('FALSE')
